package com.study.manage.dal;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;

import com.study.manage.domain.User;
import com.study.manage.domain.enumm.LiveDieState;
import com.study.manage.domain.enumm.UserType;


public interface UserRepository extends PagingAndSortingRepository<User, Long> {

    User findByPhone(String phone);

    @Query("select t from User t where t.id!=:id and t.name=:name and t.state=:state and t.type=:type")
    List<User> findByNotIdAndNameAndState(@Param("id") Long id, @Param("name") String name,
            @Param("state") LiveDieState state, @Param("type") UserType type);

    User findById(Long id);

    @Query("select t from User t where t.email=:email and t.type=2")
    User findOrgByEmail(@Param("email") String email);

    User findByNumber(Long number);

    @Query("select t from User t where (t.parentId=:parentId or t.id=:id) and t.state=:state")
    Page<User> findByParentIdOrIdAndState(@Param("parentId") Long parentId, @Param("id") Long id,
            @Param("state") LiveDieState state, Pageable pageable);

    @Query("select t from User t where t.type=:type and t.state=:state and (t.name like %:name% or :name is null)"
            + " and (:id is null or t.number=:id ) and (:parentId=0 or t.parentId is null)")
    Page<User> findByTypeAndStateAndNameAndNumberAndParentId(@Param("type") UserType type,
            @Param("state") LiveDieState state, @Param("name") String name, @Param("id") Long id,
            @Param("parentId") Integer parentId, Pageable pageable);


    Page<User> findByIdIn(@Param("id") List<Long> ids, Pageable pageable);


    @Query("select t.id from User t where t.parentId=:parentId and t.state=:state")
    List<Long> findIdByParentIdAndState(@Param("parentId") Long parentId,
            @Param("state") LiveDieState state);

}
